<template>
  <div class="about">
    <el-button @click="startAudio" type="success" :disabled="!isStart">开始录音</el-button>
    <el-button @click="stopAudio" type="danger" :disabled="!isStop">停止录音</el-button>
    <audio controls="controls" autoplay="autoplay" ref="audio"></audio>
  </div>
</template>

<script>
// import soundBuffer from '@/tools/soundBuffer.js'
// import Recorder from 'js-audio-recorder'
export default {
  data() {
    return {
      oldn: 0,
      begin: 0,
      newsize: 0,
      recorder: null,
      item: {
        name: '被爱融化的雪',
        sound: '/music/20190812/被爱融化的雪.mp3'
      },
      sourceBuffer: {},
      audioMp3:  null,
      audioSources: [],
      isStart: true,
      isStop: false
    }
  },
  async mounted() {
    // const data = await soundBuffer.getBuffer(this.item.sound)
    // if (data) {
    //   soundBuffer.createSound(data).start(0)
    // } else {
    //   console.log("download sound failed？")
    // }
    this.$nextTick(function (){
      this.audioMp3 = this.$refs.audio
      // 设置 媒体的编码类型
      var mime = 'audio/mpeg' // 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' //'video/webm; codecs="opus, vp9"'
      if ('MediaSource' in window && MediaSource.isTypeSupported(mime)) {
        let mediaSource = new MediaSource
        this.audioMp3.src = URL.createObjectURL(mediaSource)
        mediaSource.addEventListener('sourceopen', e => {  // sourceopen打开
          URL.revokeObjectURL(this.audioMp3.src)
          // var mediaSource = e.target
          this.sourceBuffer = mediaSource.addSourceBuffer(mime)
          this.sourceBuffer.appendWindowStart = 2.0
          this.sourceBuffer.appendWindowEnd = 5.0
          this.sourceBuffer.addEventListener('updateend', e => {
            console.log(this.audioSources)
            if (this.audioSources.length === 0) {
                this.audioMp3.currentTime = 0
                this.audioMp3.play()
            }
          })
        })
      } else {
        console.error('Unsupported MIME type or codec: ', mime)
      }
      //开启实时采集 每5次发送一次数据 太短的话录音文件不太完整 可以自己尝试默认8192*5=40960
      this.recorder = Recorder({
        onProcess: (buffer,size,recorder,step) => {
          if(this.oldn === 5){
            this.oldn = 0
            this.newsize = 40960
              if (step > 1) {//新采样高于录音采样不处理，省去了插值处理，直接抽样
                this.newsize = Math.floor(this.newsize / step)
              } else {
                step = 1
              }
              let res = new Int16Array(this.newsize)
              let last= this.begin
              let idx = 0
              let nl = buffer.length
              for (var n = this.begin; n < nl; n++) {
                let o = buffer[n]
                let i= last
                let il = o.length
                while(i < il) {
                  res[idx] = o[Math.round(i)]
                  idx++
                  i += step //抽样
                }
                last= i- il
              }
              this.begin = this.begin + 5
              this.recorder['mp3'](res, blob => {
                let reader = new FileReader()
                // reader.readAsDataURL(blob)
                reader.readAsArrayBuffer(blob)
                reader.onload = e => {
                  const result = e.target.result
                  console.log(result)
                  this.audioSources.push(result)
                  // socket.emit('qtsend',e.target.result)
                }
              })
          }
          this.oldn++
        }
      })
    })
  },
  methods: {
     startAudio(){
      this.isStart = false
      this.isStop = true
      this.recorder.open(() => {
        this.recorder.start()
      },function() {
        console.log('open error')
      })
    },
    stopAudio(){
      this.isStart = true
      this.isStop = false
      this.recorder.stop(blob => {
        this.audioMp3.src = URL.createObjectURL(blob)
        this.audioMp3.play()
        URL.revokeObjectURL(blob)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
